package com.balloon.springboot.ws.websocket;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.Channel;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.CommandLineRunner;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;

@Component
@Order(1)
public class NettyServer implements CommandLineRunner {

    private static final Logger logger = LoggerFactory.getLogger(NettyServer.class);

    private static NettyServer nettyServer;

    private final EventLoopGroup mainGroup;

    private final EventLoopGroup subGroup;


    @PostConstruct
    public void init(){
        nettyServer = this;
    }

    @Value("${netty.port:9093}")
    private  int port;

    private final ServerBootstrap server;

    public NettyServer(){
        mainGroup = new NioEventLoopGroup();
        subGroup = new NioEventLoopGroup();
        server = new ServerBootstrap();
        server.group(mainGroup, subGroup)
                .channel(NioServerSocketChannel.class)
                .childHandler(new NioWebSocketChannelInitializer());
    }


    public void start() {
        logger.info("通道配置,端口为{}", port);
        Channel ch = null;
        try {
            ch = server.bind(port).sync().channel();
            ch.closeFuture().sync();
        }
        catch (Exception e){
            e.printStackTrace();
        }finally {
            //优雅的退出程序
            mainGroup.shutdownGracefully();
            subGroup.shutdownGracefully();
            assert ch != null;
            ch.close();
        }
    }


    @Override
    public void run(String... args) {
        this.start();
    }

}